﻿using BasicInformation.ApiRead.Application.Command.Client;
using BasicInformation.Domain;
using BasicInformation.Dtos;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using Dapper;
using MediatR;
using System.Text;


namespace BasicInformation.ApiRead.Application.Handler.Client
    {
        public class GetClientHandler : IRequestHandler<GetClientCommand, ApiPaging<ClientModel>>
        {
            private readonly DatabaseContext db;
            private readonly ILogger<GetClientHandler> logger;

            public GetClientHandler(DatabaseContext db, ILogger<GetClientHandler> logger)
            {
                this.db = db;
                this.logger = logger;
            }

            public async Task<ApiPaging<ClientModel>> Handle(GetClientCommand request, CancellationToken cancellationToken)
            {
                ApiPaging<ClientModel> paging= new ApiPaging<ClientModel>();
                StringBuilder sql= new StringBuilder();
                StringBuilder countSql = new StringBuilder();

                // 主查询SQL
                sql.Append(@"SELECT
	                        ClientId,
	                        ClientCode,
	                        ClientName,
	                        ClientTel,
	                        ClientFax,
	                        ClientEmail,
	                        ClientContact,
	                        ClientAddr,
	                        ClientRemark 
                        FROM
	                        clientmodel 
                        WHERE
	                        IsDel = 0");

                // 计数SQL - 包含相同条件
                countSql.Append(@"SELECT COUNT(*) 
                          FROM clientmodel
                          WHERE IsDel = 0");


            // 添加查询条件 - 客户编号精确匹配
            if (!string.IsNullOrEmpty(request.ClientCode))
            {
                sql.Append(" AND ClientCode = @ClientCode");
                countSql.Append(" AND ClientCode = @ClientCode");
            }

            // 添加查询条件 - 客户名称模糊匹配
            if (!string.IsNullOrEmpty(request.ClientName))
            {
                sql.Append(" AND ClientName LIKE @ClientName");
                countSql.Append(" AND ClientName LIKE @ClientName");
            }

            if (!string.IsNullOrEmpty(request.ClientTel))
                {
                    sql.Append(" AND ClientTel LIKE @ClientTel");
                    countSql.Append(" AND ClientTel LIKE @ClientTel");
                }

                // 添加排序和分页
                sql.Append(" ORDER BY ClientId DESC LIMIT @size OFFSET @offset");

                // 设置参数
                var parameters = new
                {
                    ClientCode = request.ClientCode,
                    ClientName = string.IsNullOrEmpty(request.ClientName) ? null : $"%{request.ClientName}%",
                    ClientTel = string.IsNullOrEmpty(request.ClientTel) ? null : $"%{request.ClientTel}%",
                    offset = (request.index - 1) * request.size,
                    size = request.size
                };

                try
                {

                    // 执行查询
                    var pageData = await db.DapperConnection.QueryAsync<ClientModel>(sql.ToString(), parameters);
                    int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);
                    int totalPage = (int)Math.Ceiling(totalCount / (double)request.size);

                    // 设置返回结果
                    paging.Msg = "客户查询成功";
                    paging.Code = ApiEnum.OK;
                    paging.Data = pageData.ToList();
                    paging.TotalCount = totalCount;
                    paging.TotalPCount = totalPage;
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "客户查询失败 - SQL: {sql}, 参数: {@parameters}", sql.ToString(), parameters);
                    paging.Code = ApiEnum.Fail;
                    paging.Msg = "客户查询失败";
                }

                return paging;
            }
        }
    }
